package cn.xsly.ymcc.mq.listener;

import cn.xsly.ymcc.constants.MQConstants;
import cn.xsly.ymcc.domain.CourseOrder;
import cn.xsly.ymcc.service.ICourseOrderService;
import cn.xsly.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import okio.Utf8;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


@Component
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup = MQConstants.TX_PRODUCER_ORDER
)
public class CourseOrderListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        if (arg != null && arg instanceof CourseOrder) {
            try {
                CourseOrder order = (CourseOrder) arg;
                courseOrderService.saveOrderAndItem(order);
                return RocketMQLocalTransactionState.COMMIT;
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        AssertUtil.isNotNull(msg, "消息为空");

        byte[] bytes = (byte[]) msg.getPayload();
        CourseOrder courseOrder = null;
        try {
            String orderJson = new String(bytes, StandardCharsets.UTF_8);
            CourseOrder order = JSON.parseObject(orderJson, CourseOrder.class);
            Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
            wrapper.eq("order_no", order.getOrderNo());
            courseOrder = courseOrderService.selectOne(wrapper);
            if (courseOrder != null) {
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
